package com.chao.controller;

import com.chao.entity.User;
import com.chao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    // 返回登录 界面
    @GetMapping({"/login"})
    public String login(HttpSession session) {
        Object user = session.getAttribute("user");
        if(user != null) {
            return "main";
        }
        return "login";
    }

    // 处理登录请求
    @PostMapping("/main")
    public String main(@RequestParam("username") String username,
                       @RequestParam("password") String password,
                       HttpSession session,
                       Model model) {

        User user = userService.getById(username);
        if(user != null) {
            if(user.getPassword().equals(password)) {
                session.setAttribute("user", user);
                return "redirect:/main.html";
            }
        }
        return "redirect:/login";
    }

    // 转到首页
    @GetMapping({"/main.html","/"})
    public String GoMain() {
        return "main";
    }

    // 退出账号
    @GetMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/";
    }


}
